package com.iweb.test;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ClassName: UserServlet
 * Package: com.iweb.test
 * Description:
 *
 * @Author Jerry
 * @Create 2024/8/7 10:27
 * @Version 1.0
 */
@WebServlet(value="*.user")
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {



        String path=req.getServletPath();
        switch (path){
            case "/login.user":
                login(req,resp);
                break;
            case "/out.user":
                out(req,resp);
                break;
        }

    }
    private void login(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
        String username=req.getParameter("username");
        if(username!=null&&!"".equals(username)){
            Cookie usernameCookie=new Cookie("username",username);
            usernameCookie.setMaxAge(60);
            resp.addCookie(usernameCookie);
        }else {
            Cookie[] cookies=req.getCookies();
            if(cookies!=null&&cookies.length>0){
                for(Cookie cookie:cookies){
                    if("username".equals(cookie.getName())){
                        username=cookie.getValue();
                    }
                }
            }
        }
        if(username!=null&&!"".equals(username)){
            resp.sendRedirect(req.getContextPath()+"/success.html");
        }else{
            resp.sendRedirect(req.getContextPath()+"/login.html");
        }}

    private void out(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
        Cookie[] cookies=req.getCookies();
        if(cookies!=null&&cookies.length>0){
            for(Cookie cookie:cookies){
                if("username".equals(cookie.getName())){
                    cookie.setMaxAge(0);
                    resp.addCookie(cookie);
                }}}
        resp.sendRedirect(req.getContextPath()+"/login.html");

    }
}
